package com.css.fxfzypg.base.dict.repository.impl;

import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.base.dict.repository.DictDirectoryRepository;
import com.css.fxfzypg.base.dict.repository.entity.DictDirectoryEntity;
import com.css.fxfzypg.base.dict.viewobjects.DictDirectoryQueryParams;
import com.css.fxfzypg.util.PlatformObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Repository
public class DictDirectoryRepositoryImpl implements DictDirectoryRepository
{
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Autowired
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Override
    public Page<DictDirectoryEntity> queryDictDirectorys(DictDirectoryQueryParams queryParams, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from sys_dict_directory ");
        StringBuilder whereSql = new StringBuilder("where is_valid = '"+ YNEnum.Y.toString()+"' ");
        if(!PlatformObjectUtils.isEmpty(queryParams.getDictDirName())){
            whereSql.append(" and dict_dir_name like %"+ queryParams.getDictDirName() +"% ");
        }
        if(!PlatformObjectUtils.isEmpty(queryParams.getDictDirCode())){
            whereSql.append(" and dict_dir_code like %"+ queryParams.getDictDirCode() +"% ");
        }
        StringBuilder orderSql = new StringBuilder(" order by sort");

        String sqlWhole = sql.append(whereSql).append(orderSql).toString();

        List<DictDirectoryEntity> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<DictDirectoryEntity>(DictDirectoryEntity.class));

        Pageable pageable = PageRequest.of(curPage - 1 ,pageSize);
        Page<DictDirectoryEntity> dictDirs = new PageImpl<DictDirectoryEntity>(list, pageable,PlatformObjectUtils.isEmpty(list) ? 0 : list.size());
        return dictDirs;
    }

    @Override
    public DictDirectoryEntity findById(String parentId) {
        StringBuilder sql = new StringBuilder("select * from sys_dict_directory where dict_dir_id = '"+ parentId +"'");
        try {
            DictDirectoryEntity dictDirectoryEntity = jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper<DictDirectoryEntity>(DictDirectoryEntity.class));
            return dictDirectoryEntity;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    @Transactional
    public void save(DictDirectoryEntity directoryEntity) {
        StringBuilder sql = new StringBuilder();
        if (PlatformObjectUtils.isNotEmpty(directoryEntity) && PlatformObjectUtils.isNotEmpty(directoryEntity.getDictDirId()) && PlatformObjectUtils.isNotEmpty(findById(directoryEntity.getDictDirId())) ){
            sql.append("update sys_dict_directory set dict_dir_code = :dictDirCode, dict_dir_name = :dictDirName, " +
                    "parent_id = :parentId, all_parent_id = :allParentId, sort = :sort, description = :description, update_user = :updateUser, " +
                    "update_time = :updateTime, admin_role_id = :adminRoleId, is_valid = :isValid where dict_dir_id = :dictDirId ");
            /*Map params = new HashMap();
            params.put("dictCode", dictEntity.getDictCode());
            params.put("dictId", dictEntity.getDictId());
            namedParameterJdbcTemplate.update(updateSql.toString(), params);*/
        }else {
            sql.append("insert into sys_dict_directory values(:dictDirId , :dictDirCode, :dictDirName, :parentId" +
                    ", :allParentId, :sort, :description, :createUser, :createTime, :updateUser, :updateTime,:adminRoleId, :isValid )");
        }
        SqlParameterSource source = new BeanPropertySqlParameterSource(directoryEntity);
        //拿到新插入的主键值（i）
            /*KeyHolder keyHolder = new GeneratedKeyHolder();
            int i = namedParameterJdbcTemplate.update(sql.toString(), source, keyHolder);*/
        namedParameterJdbcTemplate.update(sql.toString(), source);
    }

    @Override
    public void deleteByAllParentIdContaining(String parentId) {
        StringBuilder sql = new StringBuilder(" delete from sys_dict_directory where all_parent_id like '%"+ parentId +"%'");
        jdbcTemplate.update(sql.toString());
    }

    @Override
    public DictDirectoryEntity findOneByDictDirCode(String dictDirCode) {
        StringBuilder sql = new StringBuilder("select * from sys_dict_directory where dict_dir_code = ?" );
        try {
            DictDirectoryEntity dictDirectoryEntity = jdbcTemplate.queryForObject(sql.toString(), new BeanPropertyRowMapper<>(DictDirectoryEntity.class), dictDirCode);
            return dictDirectoryEntity;
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }

    @Override
    public List<DictDirectoryEntity> findOrderBySort() {
        StringBuilder sql = new StringBuilder("select * from sys_dict_directory order by sort");
        List<DictDirectoryEntity> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DictDirectoryEntity.class));
        return list;
    }

    @Override
    public List<DictDirectoryEntity> findDirectorysByRoles(List<String> adminRoleId) {
        StringBuilder sql = new StringBuilder("select * from sys_dict_directory  where admin_role_id in (:ids) order by sort");
        Map idsMap = Collections.singletonMap("ids", adminRoleId);
        List<DictDirectoryEntity> list = namedParameterJdbcTemplate.query(sql.toString(), idsMap, new BeanPropertyRowMapper<>(DictDirectoryEntity.class));
        return list;
    }

    @Override
    public List<DictDirectoryEntity> findAll() {
        StringBuilder sql = new StringBuilder("select * from sys_dict_directory order by create_time ");
        List<DictDirectoryEntity> list = jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(DictDirectoryEntity.class));
        return list;
    }


}
